<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件分片</title>
</head>

<body>
  <input type="file" id="file">
  <script>
    const inputFile = document.getElementById('file')
    const CHUNK_SIZE = 1024 * 1024 * 5
    const THREAD_COUNT = navigator.hardwareConcurrency || 4

    inputFile.onchange = async e => {
      const file = e.target.files[0]
      const time = Date.now()
      console.log('开始')
      const chunk = await cutFile(file)
      console.log('结束', Date.now() - time)
      console.log(chunk)
    }

    async function cutFile(file) {
      return new Promise(resolve => {
        const chunkCount = Math.ceil(file.size / CHUNK_SIZE)
        const chunkArr = []
        const workerChunkCount = Math.ceil(chunkCount / THREAD_COUNT)
        let finishCount = 0
        for (let i = 0; i < THREAD_COUNT; i++) {
          const work = new Worker('./worker.js', { type: "module" })
          const startIndex = i * workerChunkCount
          let endIndex = startIndex + workerChunkCount
          if (endIndex > chunkCount) {
            endIndex = chunkCount
          }
          console.log(777);
          work.postMessage({
            file,
            CHUNK_SIZE,
            startIndex,
            endIndex
          })

          work.onmessage = e => {
            for (let i = startIndex; i < endIndex; i++) {
              chunkArr[i] = e.data[i - startIndex]
            }

            work.terminate()

            finishCount++

            if (finishCount === THREAD_COUNT) {
              resolve(chunkArr)
            }
          }
        }
      })

    }
  </script>
</body>

</html>